﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Inventory_Stamp : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadForm();
        }
    }
    private void loadForm()
    {
        this.btnIn.Enabled = false;
        Utils.loadProductToComboForStamp(cboProduct);
        gvData.DataSource = new DataTable();
        gvData.DataBind();

        gvStampWarehouse.DataSource = new DataTable();
        gvStampWarehouse.DataBind();

        gvDataSearch.DataSource = new DataTable();
        gvDataSearch.DataBind();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            this.btnIn.Enabled = false;
            string productID_Pack = cboProduct.SelectedValue;
            string productName = cboProduct.SelectedItem.Text;
            string productID = productID_Pack.Split('|')[0];
            string packType = productID_Pack.Split('|')[1];
            string quantity = this.txtQuantityStamp.Text;
            
            if (productID != "")
            {

                addProduct(productID,packType,productName,quantity,productID_Pack);
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Stamp-btnAdd_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void addProduct(string productID, string packType, string productName, string quantity, string productID_Pack)
    {
        DataTable dt = createDataTable();
        if (ViewState["CurrentTable"] != null)
        {

            DataRow[] rows = dt.Select("ProductID='" + productID + "' AND PackType='" + packType + "'");
            if (rows.Count() > 0)
            {
                rows[0].Delete();
                dt.AcceptChanges();
            }

            DataRow drNew = dt.NewRow();
            drNew["ProductID"] = productID;
            drNew["ProductName"] = productName;
            drNew["PackType"] = packType;
            drNew["Quantity"] = quantity;
            drNew["Key"] = productID_Pack;
            dt.Rows.Add(drNew);

            ViewState["CurrentTable"] = dt;

            if (dt.Rows.Count > 6)
            {
                RadPageView1.Height = 505;
                gvData.Height = 280;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
            }

            gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
            gvData.DataSource = dt;
            gvData.DataBind();

        }
    }
    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {
        string commandName = e.CommandName;
        string productID_Pack = e.CommandArgument.ToString();
        string productID = productID_Pack.Split('|')[0];
        string packType = productID_Pack.Split('|')[1];

        if (commandName == "EditDelItem")
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];

            DataRow[] rows = dt.Select("ProductID='" + productID + "' AND PackType='" + packType + "'");
            if (rows.Count() > 0)
            {
                rows[0].Delete();
                dt.AcceptChanges();
            }
            ViewState["CurrentTable"] = dt;
            gvData.DataSource = dt;
            gvData.DataBind();
        }
        else if (commandName == "EditItem")
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow[] rows = dt.Select("ProductID='" + productID + "' AND PackType='" + packType + "'");
            if (rows.Count() > 0)
            {
                this.cboProduct.SelectedValue = productID + "|" + packType;
                this.txtQuantityStamp.Text = rows[0]["Quantity"].ToString();
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        using (var transation = new System.Transactions.TransactionScope())
        {
            try
            {
                DBDataContext db = LINQUtil.GetDBWriteOnly();
                List<StampIn> listStampIn = new List<StampIn>();
                //List<StampWarehouse> listStampWarehouse = new List<StampWarehouse>();
                foreach (GridDataItem it in gvData.Items)
                {
                    RadNumericTextBox QuantitySelect = (RadNumericTextBox)it.FindControl("txtQuantity");
                    int Quantity = int.Parse(QuantitySelect.Text == "" ? "0" : QuantitySelect.Text.Replace(",", ""));
                    if (Quantity <= 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng cho loại tem " + it["ProductName"].Text);
                        QuantitySelect.Focus();
                        return;
                    }
                    string productID = it["ProductID"].Text;
                    string packType = it["PackType"].Text;
                    string stampName = it["ProductName"].Text;
                    StampIn stampIn = new StampIn();
                    if (ViewState["task"] != null)//edit
                    {
                        stampIn = db.StampIns.FirstOrDefault<StampIn>(a => a.ProductID.ToString() == productID && a.PackType.ToString() == packType);
                    }

                    stampIn.StampName = stampName;
                    stampIn.ProductID = int.Parse(productID);
                    stampIn.PackType = int.Parse(packType);
                    stampIn.Quantity = Quantity;
                    stampIn.Status = 'N';
                    stampIn.CreatedBy = Session["UserName"].ToString();
                    stampIn.LastUpdatedBy = Session["UserName"].ToString();
                    stampIn.CreatedDateTime = DateTime.Now;
                    stampIn.LastUpdatedDateTime = DateTime.Now;

                    listStampIn.Add(stampIn);
                }
                if (ViewState["task"] != null)//edit
                {
                    db.Update<StampIn>(listStampIn);
                }
                else
                {
                    db.Insert<StampIn>(listStampIn);
                }
                db.SubmitChanges();
                transation.Complete();
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");
                this.btnIn.Enabled = true;
            }
            catch (Exception ex)
            {
                this.btnSave.Enabled = true;
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("Stamp-btnSave_Click");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
            }
        }
    }
    protected void btnIn_Click(object sender, EventArgs e)
    {
        using (var transation = new System.Transactions.TransactionScope())
        {
            try
            {
                DBDataContext db = LINQUtil.GetDBWriteOnly();
                List<StampWarehouse> listStampWarehouse = new List<StampWarehouse>();
                List<StampIn> listStampIn = new List<StampIn>();
                foreach (GridDataItem it in gvData.Items)
                {
                    RadNumericTextBox QuantitySelect = (RadNumericTextBox)it.FindControl("txtQuantity");
                    int Quantity = int.Parse(QuantitySelect.Text == "" ? "0" : QuantitySelect.Text.Replace(",", ""));
                    if (Quantity <= 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng cho loại tem " + it["ProductName"].Text);
                        QuantitySelect.Focus();
                        return;
                    }

                    StampWarehouse stampWarehouse = db.StampWarehouses.FirstOrDefault<StampWarehouse>(a => a.ProductID == int.Parse(it["ProductID"].Text) && a.PackType == int.Parse(it["PackType"].Text));
                    if (stampWarehouse == null)
                    {
                        stampWarehouse = new StampWarehouse();
                        stampWarehouse.CreatedBy = Session["UserName"].ToString();
                        stampWarehouse.CreatedDateTime = DateTime.Now;
                        stampWarehouse.Quantity = Quantity;
                    }
                    else
                    {
                        stampWarehouse.Quantity = stampWarehouse.Quantity + Quantity;
                        db.Delete<StampWarehouse>(stampWarehouse);

                    }
                    string stampName = it["ProductName"].Text;
                    stampWarehouse.StampName = stampName;
                    stampWarehouse.ProductID = int.Parse(it["ProductID"].Text);
                    stampWarehouse.PackType = int.Parse(it["PackType"].Text);

                    stampWarehouse.Status = 'A';
                    stampWarehouse.LastUpdatedBy = Session["UserName"].ToString();
                    stampWarehouse.LastUpdatedDateTime = DateTime.Now;

                    listStampWarehouse.Add(stampWarehouse);


                    StampIn stampIn = db.StampIns.FirstOrDefault<StampIn>(a => a.ProductID == int.Parse(it["ProductID"].Text) && a.PackType == int.Parse(it["PackType"].Text));
                    if (stampIn != null)
                    {
                        stampIn.Status = 'A';
                        stampIn.LastUpdatedBy = Session["UserName"].ToString();
                        stampIn.LastUpdatedDateTime = DateTime.Now;

                        listStampIn.Add(stampIn);
                    }

                }
                db.Insert<StampWarehouse>(listStampWarehouse);
                db.Update<StampIn>(listStampIn);
                db.SubmitChanges();
                transation.Complete();
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");

                this.btnIn.Enabled = false;
                this.btnSave.Enabled = false;
                this.btnAddProduct.Enabled = false;
                this.gvData.Enabled = false;
            }
            catch (Exception ex)
            {
                this.btnIn.Enabled = true;
                this.btnSave.Enabled = true;
                this.btnAddProduct.Enabled = true;
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("Stamp-btnSave_Click");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
            }
        }
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Quan-ly-tem", false);
    }

    private DataTable createDataTable()
    {
        DataTable dt = new DataTable();
        if (ViewState["CurrentTable"] == null)
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("PackType");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("Key");
            ViewState["CurrentTable"] = dt;
        }
        else
        {
            dt = (DataTable)ViewState["CurrentTable"];
        }
        return dt;
    }

    /*Xem thong tin ton kho tem*/

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        gvStampWarehouse.CurrentPageIndex = 0;
        loadData();
        gvStampWarehouse.DataBind();
    }

    private void loadData()
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        string stampName = this.txtStamp.Text;
        int PageNumber = gvStampWarehouse.CurrentPageIndex + 1;
        int PageSize = gvStampWarehouse.PageSize;
        int fromQty = this.txtQuantityFrom.Text == "" ? -99999999 : int.Parse(this.txtQuantityFrom.Text);
        int toQty = this.txtQuantityTo.Text == "" ? 99999999 : int.Parse(this.txtQuantityTo.Text);
        var list = (db.StampWarehouse_Search(stampName, fromQty, toQty, PageSize, PageNumber)).ToList();
        if (list.Count > 6)
        {
            //gvStampWarehouse.Height = 280;
            gvStampWarehouse.ClientSettings.Scrolling.AllowScroll = true;
            gvStampWarehouse.ClientSettings.Scrolling.UseStaticHeaders = true;
        }
        if (list.Count > 0)
        {
            gvStampWarehouse.VirtualItemCount = list[0].TotalRows.Value;
        }
        gvStampWarehouse.DataSource = list;
                    
    }
    protected void gvStampWarehouse_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        loadData();
        //LoadData();
    }

    protected void btnSearchStampIn_Click(object sender, EventArgs e)
    {
        gvDataSearch.CurrentPageIndex = 0;
        loadDataSearch();
        gvDataSearch.DataBind();
    }
    protected void gvDataSearch_ItemCommand(object sender, GridCommandEventArgs e)
    {
        try
        {
            string commandName = e.CommandName;
            GridDataItem item = e.Item as GridDataItem;
            String key = e.CommandArgument.ToString();
            DBDataContext db = LINQUtil.GetDBWriteOnly();
            if (commandName == "DelItem")
            {
                var s = db.StampIns.FirstOrDefault<StampIn>(a=>(a.ProductID.ToString()+"|"+a.PackType.ToString()) == key);
                if (s != null)
                {
                    db.Delete<StampIn>(s);
                    db.SubmitChanges();
                    
                    loadDataSearch();
                    gvDataSearch.DataBind();
                }
            }
            else if (commandName == "EditItem")
            {
                RadPageView1.Selected = true;
                TabStrip1.SelectedIndex = 1;
                this.cboProduct.Visible = false;
                this.txtQuantityStamp.Visible = false;
                this.btnAddProduct.Visible = false;
                this.btnIn.Enabled = true;
                
                gvData.Columns[5].Visible = false;
                gvData.Columns[6].Visible = false;
                 var s = db.StampIns.FirstOrDefault<StampIn>(a=>(a.ProductID.ToString()+"|"+a.PackType.ToString()) == key);
                 if (s != null)
                 {
                     ViewState["task"] = "Edit";
                     ViewState["CurrentTable"] = null;
                     addProduct(s.ProductID.ToString(), s.PackType.ToString(), s.StampName, s.Quantity.ToString(), key);
                    
                 }
                 foreach (GridDataItem it in gvData.Items)
                 {
                     RadNumericTextBox txtQuantity = (RadNumericTextBox)it.FindControl("txtQuantity");
                     txtQuantity.Enabled = true;
                 }
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("Stamp-gvDataSearch_ItemCommand");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
        }
    }
    protected void gvDataSearch_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        loadDataSearch();
    }
    protected void gvDataSearch_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = (GridDataItem)e.Item;
            string status = item["StatusCode"].Text.ToString();
            Button DeleteCol = (Button)item.FindControl("btnDelStamp");
            Button EditCol = (Button)item.FindControl("btnEditStamp");
            if (status != "N")
            {
                DeleteCol.Visible = false;
                EditCol.Visible = false;
            }
        }
    }
    private void loadDataSearch()
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        string stampName = this.txtTypeStampSearch.Text;
        string userIn = this.txtUserIn.Text;
        DateTime? vFromDate = dtFromDate.SelectedDate.HasValue?dtFromDate.SelectedDate:new DateTime(2014,1,1);
        DateTime? vToDate = dtToDate.SelectedDate.HasValue ? dtToDate.SelectedDate : new DateTime(2099, 1, 1);
        int PageNumber = gvDataSearch.CurrentPageIndex + 1;
        int PageSize = gvDataSearch.PageSize;
        var q = db.StampIn_Search(stampName, vFromDate, vToDate, userIn, PageSize, PageNumber).ToList();
        if (q.Count > 0)
        {
            if (q.Count > 6)
            {
                gvDataSearch.Height = 505;
                gvDataSearch.Height = 280;
                gvDataSearch.ClientSettings.Scrolling.AllowScroll = true;
                gvDataSearch.ClientSettings.Scrolling.UseStaticHeaders = true;
            }
            gvDataSearch.VirtualItemCount = q[0].TotalRows.Value;
            gvDataSearch.DataSource = q;
        }
        else
        {
            gvDataSearch.DataSource = new DataTable();
        }

    }

}